<template>
  <el-dialog
    v-model="dialogVisible"
    title="分享成绩"
    width="500px"
    :before-close="handleClose"
  >
    <div class="share-dialog">
      <!-- 成绩预览卡片 -->
      <div class="score-preview-card">
        <div class="card-header">
          <div class="project-info">
            <span class="project-name">{{ score?.project?.name || '-' }}</span>
            <el-tag size="small" :type="getStatusType(score?.status)">
              {{ getStatusText(score?.status) }}
            </el-tag>
          </div>
          <div class="ranking" v-if="score?.rank">
            <span class="rank-badge" :class="getRankingClass(score.rank)">
              <span v-if="score.rank <= 3" class="medal">{{ getMedalIcon(score.rank) }}</span>
              <span v-else class="rank-number">第{{ score.rank }}名</span>
            </span>
          </div>
        </div>

        <div class="card-content">
          <div class="student-section">
            <div class="student-avatar">
              <el-avatar :size="50" :src="score?.student?.avatar">
                {{ score?.student?.name?.charAt(0) || '学' }}
              </el-avatar>
            </div>
            <div class="student-info">
              <div class="student-name">{{ score?.student?.name || '-' }}</div>
              <div class="student-details">
                <div class="student-id">{{ score?.student?.studentNumber || '-' }}</div>
                <div class="student-department">{{ score?.student?.department || '-' }}</div>
              </div>
            </div>
          </div>

          <div class="score-section">
            <div class="score-display">
              <span class="score-value" :class="{ 'record-breaking': score?.isRecord }">
                {{ score?.score || '-' }}
              </span>
              <span class="score-unit">{{ score?.unit || '' }}</span>
              <el-tag v-if="score?.isRecord" type="danger" size="small" class="record-tag">
                <el-icon><Trophy /></el-icon> 破纪录
              </el-tag>
            </div>
            <div class="score-meta">
              <span class="round-info">{{ getRoundText(score?.round) }}</span>
              <span class="time-info">{{ formatDateTime(score?.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分享选项 -->
      <div class="share-options">
        <h3 class="section-title">分享方式</h3>

        <el-tabs v-model="shareType" type="border-card">
          <!-- 链接分享 -->
          <el-tab-pane label="链接分享" name="link">
            <div class="share-link-section">
              <div class="link-preview">
                <el-input
                  v-model="shareLink"
                  readonly
                  :suffix-icon="CopyDocument"
                  @click="copyShareLink"
                >
                  <template #prepend>
                    <el-icon><Link /></el-icon>
                  </template>
                </el-input>
                <el-button type="primary" @click="copyShareLink" :loading="copying">
                  <el-icon><CopyDocument /></el-icon> 复制链接
                </el-button>
              </div>

              <div class="link-settings">
                <el-form :model="linkSettings" label-width="100px" size="small">
                  <el-form-item label="有效期">
                    <el-select v-model="linkSettings.expiry">
                      <el-option label="1天" value="1d" />
                      <el-option label="7天" value="7d" />
                      <el-option label="30天" value="30d" />
                      <el-option label="永久" value="permanent" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="访问密码">
                    <el-input v-model="linkSettings.password" placeholder="留空则无需密码" />
                  </el-form-item>
                  <el-form-item label="访问限制">
                    <el-input-number v-model="linkSettings.accessLimit" :min="1" :max="1000" placeholder="无限制" />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-tab-pane>

          <!-- 二维码分享 -->
          <el-tab-pane label="二维码分享" name="qrcode">
            <div class="share-qrcode-section">
              <div class="qrcode-container">
                <div ref="qrcodeRef" class="qrcode"></div>
                <div class="qrcode-tips">
                  <p>扫描二维码查看成绩详情</p>
                  <el-button type="primary" size="small" @click="downloadQRCode">
                    <el-icon><Download /></el-icon> 下载二维码
                  </el-button>
                </div>
              </div>

              <div class="qrcode-settings">
                <el-form :model="qrcodeSettings" label-width="100px" size="small">
                  <el-form-item label="二维码尺寸">
                    <el-radio-group v-model="qrcodeSettings.size">
                      <el-radio-button label="small">小</el-radio-button>
                      <el-radio-button label="medium">中</el-radio-button>
                      <el-radio-button label="large">大</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="Logo">
                    <el-switch v-model="qrcodeSettings.includeLogo" />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-tab-pane>

          <!-- 社交媒体分享 -->
          <el-tab-pane label="社交媒体" name="social">
            <div class="share-social-section">
              <div class="social-platforms">
                <div class="platform-item" @click="shareToWeChat">
                  <div class="platform-icon wechat">
                    <el-icon><ChatDotSquare /></el-icon>
                  </div>
                  <span>微信</span>
                </div>
                <div class="platform-item" @click="shareToQQ">
                  <div class="platform-icon qq">
                    <el-icon><ChatDotRound /></el-icon>
                  </div>
                  <span>QQ</span>
                </div>
                <div class="platform-item" @click="shareToWeibo">
                  <div class="platform-icon weibo">
                    <el-icon><Share /></el-icon>
                  </div>
                  <span>微博</span>
                </div>
                <div class="platform-item" @click="shareToEmail">
                  <div class="platform-icon email">
                    <el-icon><Message /></el-icon>
                  </div>
                  <span>邮件</span>
                </div>
              </div>

              <div class="share-text">
                <el-input
                  v-model="shareText"
                  type="textarea"
                  :rows="3"
                  placeholder="自定义分享文案..."
                  maxlength="200"
                  show-word-limit
                />
              </div>
            </div>
          </el-tab-pane>

          <!-- 导出分享 -->
          <el-tab-pane label="导出分享" name="export">
            <div class="share-export-section">
              <div class="export-options">
                <el-radio-group v-model="exportFormat" direction="vertical">
                  <el-radio label="pdf">PDF文件</el-radio>
                  <el-radio label="image">图片文件</el-radio>
                  <el-radio label="excel">Excel表格</el-radio>
                </el-radio-group>
              </div>
              <div class="export-actions">
                <el-button type="primary" @click="exportScore" :loading="exporting">
                  <el-icon><Download /></el-icon> 导出文件
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmShare">确认分享</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Trophy, Link, CopyDocument, Download, ChatDotSquare,
  ChatDotRound, Share, Message
} from '@element-plus/icons-vue'
import * as QRCode from 'qrcode'
import { generateShareLink as generateShareLinkAPI } from '@/api/score'

// 组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  score: {
    type: Object,
    default: () => ({})
  }
})

// 组件事件
const emit = defineEmits(['update:modelValue', 'close'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 分享类型
const shareType = ref('link')

// 二维码引用
const qrcodeRef = ref(null)

// 分享链接
const shareLink = ref('')
const copying = ref(false)

// 链接设置
const linkSettings = reactive({
  expiry: '7d',
  password: '',
  accessLimit: null
})

// 二维码设置
const qrcodeSettings = reactive({
  size: 'medium',
  includeLogo: true
})

// 分享文本
const shareText = ref('')

// 导出格式
const exportFormat = ref('pdf')
const exporting = ref(false)

// 获取排名样式类
const getRankingClass = (rank) => {
  if (rank === 1) return 'gold'
  if (rank === 2) return 'silver'
  if (rank === 3) return 'bronze'
  return ''
}

// 获取奖牌图标
const getMedalIcon = (rank) => {
  if (rank === 1) return '🥇'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return ''
}

// 获取轮次文本
const getRoundText = (round) => {
  const roundMap = {
    1: '第1轮',
    2: '第2轮',
    3: '第3轮',
    4: '决赛'
  }
  return roundMap[round] || '-'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'PUBLISHED': 'success',
    'REJECTED': 'danger',
    'DISPUTED': 'info'
  }
  return typeMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待审核',
    'PUBLISHED': '已公示',
    'REJECTED': '已驳回',
    'DISPUTED': '有异议'
  }
  return textMap[status] || '-'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生成分享链接
const generateShareLinkHandler = async () => {
  try {
    const response = await generateShareLinkAPI({
      scoreId: props.score?.id,
      ...linkSettings
    })

    if (response.code === 200) {
      shareLink.value = response.data.link || ''
      // 初始化分享文本
      if (!shareText.value) {
        shareText.value = `我在校园运动会${props.score?.project?.name}中取得了${props.score?.score}${props.score?.unit || ''}的成绩！`
      }
    } else {
      ElMessage.error(response.message || '生成分享链接失败')
    }
  } catch (error) {
    console.error('生成分享链接失败:', error)
    ElMessage.error('生成分享链接失败')
  }
}

// 生成二维码
const generateQRCode = async () => {
  if (!qrcodeRef.value || !shareLink.value) return

  try {
    const sizeMap = {
      small: 150,
      medium: 200,
      large: 250
    }

    await QRCode.toCanvas(qrcodeRef.value, shareLink.value, {
      width: sizeMap[qrcodeSettings.size],
      margin: 2,
      color: {
        dark: '#2c3e50',
        light: '#ffffff'
      }
    })
  } catch (error) {
    console.error('生成二维码失败:', error)
    ElMessage.error('生成二维码失败')
  }
}

// 复制分享链接
const copyShareLink = async () => {
  if (!shareLink.value) {
    ElMessage.warning('请先生成分享链接')
    return
  }

  copying.value = true
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  } finally {
    copying.value = false
  }
}

// 下载二维码
const downloadQRCode = () => {
  if (!qrcodeRef.value) return

  const canvas = qrcodeRef.value
  const url = canvas.toDataURL('image/png')
  const link = document.createElement('a')
  link.href = url
  link.download = `成绩二维码_${props.score?.student?.name}_${new Date().toLocaleDateString()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  ElMessage.success('二维码下载成功')
}

// 分享到微信
const shareToWeChat = () => {
  ElMessage.info('请使用微信扫描二维码分享')
}

// 分享到QQ
const shareToQQ = () => {
  const url = `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(shareLink.value)}&title=${encodeURIComponent(shareText.value)}`
  window.open(url, '_blank')
}

// 分享到微博
const shareToWeibo = () => {
  const url = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(shareLink.value)}&title=${encodeURIComponent(shareText.value)}`
  window.open(url, '_blank')
}

// 分享到邮件
const shareToEmail = () => {
  const subject = encodeURIComponent('校园运动会成绩分享')
  const body = encodeURIComponent(`${shareText.value}\n\n详情链接：${shareLink.value}`)
  window.location.href = `mailto:?subject=${subject}&body=${body}`
}

// 导出成绩
const exportScore = async () => {
  exporting.value = true
  try {
    // 这里应该调用导出API
    // 模拟导出过程
    setTimeout(() => {
      ElMessage.success('导出成功')
      exporting.value = false
    }, 1500)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
    exporting.value = false
  }
}

// 确认分享
const confirmShare = () => {
  ElMessage.success('分享成功')
  handleClose()
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  emit('close')
}

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible && props.score?.id) {
    generateShareLinkHandler()
  }
})

// 监听分享链接变化
watch(shareLink, () => {
  if (shareLink.value) {
    nextTick(() => {
      generateQRCode()
    })
  }
})

// 监听二维码设置变化
watch(qrcodeSettings, () => {
  if (shareLink.value) {
    generateQRCode()
  }
}, { deep: true })

// 组件挂载
onMounted(() => {
  if (props.score?.id) {
    generateShareLinkHandler()
  }
})
</script>

<style scoped>
.share-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

/* 成绩预览卡片 */
.score-preview-card {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.project-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.project-name {
  font-weight: 600;
  font-size: 16px;
  color: #2c3e50;
}

.ranking {
  display: flex;
  align-items: center;
}

.rank-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  height: 40px;
  border-radius: 50%;
  font-weight: bold;
}

.rank-badge.gold {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

.rank-badge.silver {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #696969;
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.3);
}

.rank-badge.bronze {
  background: linear-gradient(135deg, #cd7f32, #e4a853);
  color: #8b4513;
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.3);
}

.medal {
  font-size: 20px;
}

.rank-number {
  font-size: 12px;
  padding: 0 8px;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.student-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.student-info {
  flex: 1;
}

.student-name {
  font-weight: 500;
  font-size: 16px;
  color: #2c3e50;
  margin-bottom: 4px;
}

.student-details {
  font-size: 12px;
  color: #7f8c8d;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.score-section {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
}

.score-display {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.score-value.record-breaking {
  color: #e74c3c;
  animation: pulse 1.5s infinite;
}

.score-unit {
  font-size: 14px;
  color: #7f8c8d;
}

.record-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.score-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #7f8c8d;
}

/* 分享选项 */
.share-options {
  margin-top: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
}

/* 链接分享 */
.share-link-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.link-preview {
  display: flex;
  gap: 12px;
  align-items: center;
}

.link-settings {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

/* 二维码分享 */
.share-qrcode-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.qrcode-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.qrcode {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 10px;
  background-color: white;
}

.qrcode-tips {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.qrcode-tips p {
  margin: 0;
  color: #7f8c8d;
}

.qrcode-settings {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

/* 社交媒体分享 */
.share-social-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.social-platforms {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.platform-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.platform-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.platform-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.platform-icon.wechat {
  background: linear-gradient(135deg, #07c160, #06ae56);
}

.platform-icon.qq {
  background: linear-gradient(135deg, #12b7f5, #1296db);
}

.platform-icon.weibo {
  background: linear-gradient(135deg, #ff8200, #ff6700);
}

.platform-icon.email {
  background: linear-gradient(135deg, #4285f4, #1967d2);
}

.share-text {
  margin-top: 16px;
}

/* 导出分享 */
.share-export-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.export-options {
  flex: 1;
}

.export-actions {
  display: flex;
  align-items: center;
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .social-platforms {
    grid-template-columns: repeat(2, 1fr);
  }

  .link-preview {
    flex-direction: column;
    align-items: stretch;
  }

  .qrcode-container {
    flex-direction: column;
    text-align: center;
  }

  .share-export-section {
    flex-direction: column;
  }
}
</style>